package com.prodog.usermodule.role.interceptor;

import com.prodog.command.entity.GameCommand;
import com.prodog.command.entity.RoleGameCommand;
import com.prodog.command.interceptor.Interceptor;
import com.prodog.command.interceptor.InterceptorRes;
import com.prodog.gamemodule.config.MapDictConfig;
import com.prodog.usermodule.role.entity.RoleInfo;
import com.prodog.usermodule.role.wrapper.RoleInfoWrapper;
import com.prodog.usermodule.user.entity.UserInfo;
import com.prodog.usermodule.user.wrapper.UserInfoWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class StateInterceptor implements Interceptor {
    private final RoleInfoWrapper roleInfoWrapper;
    private final UserInfoWrapper userInfoWrapper;
    private final MapDictConfig mapDictConfig;

    @Override
    public InterceptorRes intercept(GameCommand command, Map<String, Object> params, String formatMsg) {
        RoleInfo roleInfo = null;
        if (command instanceof RoleGameCommand) {
            roleInfo = ((RoleGameCommand) command).getRoleInfo();
        }
        if (roleInfo == null) {
            UserInfo userInfo = userInfoWrapper.getById(command.getFromQQ());
            roleInfo = roleInfoWrapper.getById(userInfo.getRoleId());
        }
        List<Integer> requiredStates = (List<Integer>) params.get("requiredStates");

        RoleInfo finalRoleInfo = roleInfo;
        boolean res = requiredStates.stream().anyMatch(state -> state.equals(finalRoleInfo.getState()));
        return res ? InterceptorRes.pass() : InterceptorRes.intercept((roleInfo.getPrefix() + formatMsg).replace("{{state}}", mapDictConfig.get("roleState", roleInfo.getState())));
    }
}
